<template>
<!--    <el-button @click="visible = true">-->
<!--        Open Drawer with customized header-->
<!--    </el-button>-->
    <el-drawer v-model="visible" :show-close="false">
        <template #header="{ close, titleId, titleClass }">
            <h4 :id="titleId" :class="titleClass">发布帖子</h4>
            <el-button type="danger" @click="close">
                <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
                关闭
            </el-button>
        </template>
        <div class="post-container">
            <form>
                <div class="form-group">
                    <label for="title">标题：</label>
                    <el-input v-model="postTitle" placeholder="标题" />
                </div>
                <div class="form-group">
                    <label for="content">内容：</label>
                    <el-input
                            v-model="postContent"
                            :rows="3"
                            type="textarea"
                            placeholder="内容"
                    />
                </div>
              <div>
                <el-select
                    v-model="relatedStock"
                    filterable
                    placeholder="与帖子相关联的股票"
                    style="width: 240px;margin-bottom: 12px;"
                >
                  <el-option
                      v-for="item in optionalStocks"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </div>
                <div class="form-group">
                    <label for="image">附带图片：</label>
                    <input type="file" id="image" @change="handleImageUpload" accept="image/*" multiple>
                    <div v-if="previewImages.length > 0" style="display: flex;flex-wrap: wrap;">
                        <div class="preImg" v-for="(previewImage, index) in previewImages" :key="index">
                            <img :src="previewImage" alt="帖子图片预览" class="preview-image">
                            <div class="deleteImg" @click="removeImage(index)">删除</div>
                        </div>
                    </div>
                </div>
                <div @click="submitPost" class="deleteImg PublishMessage">发布帖子</div>
            </form>
        </div>
    </el-drawer>
</template>

<script setup>
    import {ref, watch,defineEmits} from 'vue'
    import {ElButton, ElDrawer, ElMessage, ElNotification} from 'element-plus'
    import { CircleCloseFilled } from '@element-plus/icons-vue'
    import {useCounterStore} from "@/stores/counter.js"
    import {getOptionalStockList, postForum, uploadAvatarService} from "@/api/request.js";

    const CounterStore=useCounterStore()
    const visible = ref(false)
    watch(()=>CounterStore.openPublishForum,()=>{
        if(CounterStore.openPublishForum===true){
            visible.value=true
        }
    })
    watch(visible,()=>{
        if(visible.value===false){
            CounterStore.openPublishForum=false
        }
    })

    const postTitle = ref('');
    const postContent = ref('');
    const previewImages = ref([]);
    const imageFiles = ref([]);
    let relatedStock=ref(null)

    // 图片上传文件数组
    let imgUploadFiles=[]

    // 查看图片
    const handleImageUpload = (event) => {
        const files = event.target.files;
        if (files && files.length > 0) {
          imgUploadFiles.push(files[0])
            const newFiles = Array.from(files);
            const newReaders = [];
            for (const file of newFiles) {
                const reader = new FileReader();
                newReaders.push(reader);
                reader.onload = (e) => {
                    previewImages.value.push(e.target.result);
                    imageFiles.value.push(file);
                };
                reader.readAsDataURL(file);
            }
        }
    };

    // 图片上传阿里云oss服务器，返回图片链接数组
    async function UploadImgToAlibaba() {
      let ImgAllUrls="";
      for (let i = 0; i < imgUploadFiles.length; i++) {
        let url = await uploadAvatarService(imgUploadFiles[i])
        ImgAllUrls=ImgAllUrls+url+"||"
      }
      return ImgAllUrls;
    }

    // 删除图片预览
    const removeImage = (index) => {
        previewImages.value.splice(index, 1);
        imageFiles.value.splice(index, 1);
    };

    // 控制帖子发布按钮是否可以点击，防止多次提交
    let ifSubmit=true
    // 发布帖子
    const submitPost = async () => {
      if(!ifSubmit){
        return;
      }else {
        ifSubmit=false
      }
      if(postTitle.value===""){
        ElMessage.error('标题不能为空')
        return;
      }
      if(postContent.value===""){
        ElMessage.error('内容不能为空')
        return;
      }
        try {
          let message={
            title:postTitle.value,
            content:postContent.value,
            stockId:relatedStock.value,
            imageUrl:await UploadImgToAlibaba()
          }
          await postForum(message)
          sendMessage()
          ElNotification({
            title: '成功',
            message: '发布成功',
            duration: 0,
          });
            postTitle.value = '';
            postContent.value = '';
            previewImages.value = [];
            imageFiles.value = [];
          relatedStock.value=null
          imgUploadFiles=[]
            visible.value = false;
          ifSubmit=true
        } catch (error) {
            ElMessage.error('发布失败');
            ifSubmit=true
        }
    };

    let optionalStocks=ref([])
    // 获取可选股票列表
    async function getstockInfoList() {
      if(!sessionStorage.getItem('token')){
        return;
      }
      let message={userId:CounterStore.UserMessage.id}
      let data = (await getOptionalStockList(message)).records
      for (let i = 0; i < data.length; i++) {
        optionalStocks.value.push({
          value: data[i].stockId,
          label: data[i].stockCode+' '+data[i].stockName
        })
      }
    }
    getstockInfoList()

    const emit = defineEmits(['message-sent']);
    function sendMessage() {
      emit('message-sent', true);
    }

</script>

<style scoped>
    .post-container {
        max-width: 600px;
        padding: 20px;
        border-radius: 5px;
        background-color: #fbfbfb;
        box-shadow: 0 0 5px rgb(0 0 0 / 10%);
    }
    .form-group {
        margin-bottom: 15px;
    }
    label {
        display: block;
        margin-bottom: 5px;
    }
    input,
    textarea {
        width: 100%;
        padding: 8px;
        border: 1px solid #ccc;
        border-radius: 3px;
    }
    .preview-image {
        max-width: 95%;
        margin-top: 10px;
    }
    .deleteImg {
        padding: 5px 5px;
        background-color: #007BFF;
        color: white;
        border: none;
        border-radius: 3px;
        width: 23%;
        cursor: pointer;
        text-align: center;
        font-size: 12px;
    }
    .deleteImg:hover {
        background-color: #0056b3;
    }
    .preImg{
        width: 163px;
        margin-left: 16px;
    }
    .PublishMessage{
        padding: 7px;
        font-size: 16px;
    }
    .chooseStock{
      margin-bottom: 15px;
    }
</style>